package com.sundroid.utils.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.sundroid.utils.common.PropertiesUtils;

public class JdbcUtil {

	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	public static java.sql.Connection getConnection() {

		Connection conn = null;
		PropertiesUtils.loadFile("jdbc.properties");
		String url = PropertiesUtils.getPropertyValue("url");

		String UserName = PropertiesUtils.getPropertyValue("username");

		String Password = PropertiesUtils.getPropertyValue("password");

		try {
			Class.forName(PropertiesUtils.getPropertyValue("driverClassName"));

			conn = DriverManager.getConnection(url, UserName, Password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return conn;
	}

	public static void beginTransaction() throws SQLException {
		Connection con = tl.get();

		if (con != null)
			throw new SQLException("开启事务异常");
		con = getConnection();
		con.setAutoCommit(false);

		tl.set(con);
	}

	public static void commitTransaction() throws SQLException {
		Connection con = tl.get();
		if (con == null)
			throw new SQLException("提交事务异常");
		con.commit();
		con.close();
		con = null;
		tl.remove();
	}

	public static void rollbackTransaction() throws SQLException {
		Connection con = tl.get();
		if (con == null)
			throw new SQLException("回滚事务异常");
		con.rollback();
		con.close();
		con = null;
		tl.remove();
	}

	public static void releaseConnection(Connection connection)
			throws SQLException {
		Connection con = tl.get();
		if (connection != con) {
			if (connection != null && !connection.isClosed()) {
				connection.close();
			}
		}
	}

}
